#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv)
{
    unsigned char buffer1[4], buffer2[4];
    int fd1, fd2;
    int ret = 0;
    int i;

    fd1 = open(argv[1], O_RDWR|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
    if(-1 == fd1){
        perror("open error");
        exit(-1);
    }

    fd2 = open(argv[1], O_RDWR);
    if(-1 == fd2){
        perror("open error");
        ret = -1;
        goto err1;
    }

    buffer1[0] = 0x11;
    buffer1[1] = 0x22;
    buffer1[2] = 0x33;
    buffer1[3] = 0x44;

    buffer2[0] = 0xAA;
    buffer2[1] = 0xBB;
    buffer2[2] = 0xCC;
    buffer2[3] = 0xDD;

    for(i=0; i<4; i++){
        ret = write(fd1, buffer1, sizeof(buffer1));
        if(-1 == ret){
            perror("write fd1 error");
            goto err2;
        }

        ret = write(fd2, buffer2, sizeof(buffer2));
        if(-1 == ret){
            perror("write fd2 error");
            goto err2;
        }
    }

    ret = lseek(fd1, 0, SEEK_SET);
    if(-1 == ret){
        perror("lseek fd1 error");
        goto err2;
    }

    for(i=0; i<8; i++){
        ret = read(fd1, buffer1, sizeof(buffer1));
        if(-1 == ret){
            perror("read error");
            goto err2;
        }

        printf("0x%x, 0x%x, 0x%x, 0x%x\n", buffer1[0],buffer1[1],buffer1[2],buffer1[3]);
    }

    printf("\n");
    ret = 0;

    err2:
        close(fd1);
        close(fd2);

    err1:
        close(fd1);
        exit(ret);

    exit(ret);
}
